import SqliteHelper from "@/sqlite/SqliteHelper";
import type { MaterialType } from "@/typings/businessType";
import type { TableFieldsOption } from "@anlib/sqlite-orm/lib/types";
import type { DatabaseParams } from "react-native-sqlite-storage";

// 素材数据
const databaseParams: DatabaseParams = {
  name: "material.db",
  location: "default"
};

// 本地保存的字段数据, 具体类型见下面定义
const fields: TableFieldsOption[] = [
  { field: "id", type: "INTEGER", isKey: true },

  { field: "sourceId", type: "VARCHAR" },
  { field: "parentCode", type: "VARCHAR" },
  { field: "officeName", type: "VARCHAR" },
  { field: "officeCode", type: "VARCHAR" },
  { field: "code", type: "VARCHAR" },
  { field: "name", type: "VARCHAR" },
  { field: "type", type: "VARCHAR" },
  { field: "isUnAudit", type: "VARCHAR" },
  { field: "isShim", type: "VARCHAR" },
  { field: "putLibTime", type: "VARCHAR" },
  { field: "duration", type: "VARCHAR" },
  { field: "size", type: "VARCHAR" },
  { field: "resolution", type: "VARCHAR" },
  { field: "file", type: "VARCHAR" },
  { field: "auditFlag", type: "VARCHAR" },
  { field: "remarks", type: "VARCHAR" },
  { field: "status", type: "VARCHAR" },

  { field: "startTime", type: "VARCHAR" },
  { field: "endTime", type: "VARCHAR" },
  { field: "sort", type: "INTEGER" },

  { field: "fileName", type: "VARCHAR" },
  { field: "downFileToNativePath", type: "VARCHAR" },
  { field: "downFileUrl", type: "VARCHAR" },
  { field: "isChunkDown", type: "VARCHAR" },
  { field: "isDown", type: "VARCHAR" },
];

// 初始化 sqlite
let sqlh: SqliteHelper | null = null;
const initSqlite = (): Promise<SqliteHelper> => {
  return new Promise((resolve, reject) => {
    const instance = new SqliteHelper(databaseParams, fields, 1);

    // 初始化
    instance
      .init()
      .then(res => {
        if (res instanceof SqliteHelper) {
          sqlh = res;
          resolve(sqlh);
        } else {
          reject(res);
        }
      })
      .catch(err => {
        reject(err);
      });
  });
};

// 关闭数据库
const closeSqlite = () => {
  if (sqlh) {
    sqlh.close();
    sqlh = null;
  }
};

// 定义sqling 数据的 ts 类型
type MaterialSqliteType = Omit<MaterialType, "id"> & {
  /** sqlite id */
  id: number;
  /** 数据原始id */
  sourceId: string;
  /** 关联排期code */
  parentCode: string;

  /** 开始时间, 时:分:秒 */
  startTime: string;
  /** 结束时间, 时:分:秒 */
  endTime: string;
  /** 排序 */
  sort: number;

  /** 
   * 文件名称, 取的是素材下载地址的 name 参数
   */
  fileName: string;
  /** 
   * 素材文件下载到那个路径, 命名规则: 
   * Download/${config.resourceDir}/${排期code}/${素材name}
   */
  downFileToNativePath: string;
  /** 文件下载的URL */
  downFileUrl: string;
  /** 
   * 是否使用分片下载
   * - 1 不使用
   * - 2 使用
   */
  isChunkDown: "1" | "2";
  /** 
   * 是否已经下载
   * - 1 否
   * - 2 是
   */
  isDown: "1" | "2";

  // TODO 指定日期下载, 还是随时下载
};

export { sqlh, initSqlite, closeSqlite, type MaterialSqliteType };
